package com.xnx3.wangmarket.plugin.ainewspublish.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xnx3.Lang;
import com.xnx3.StringUtil;
import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.util.SpringUtil;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.wangmarket.admin.entity.News;
import com.xnx3.wangmarket.admin.entity.Site;
import com.xnx3.wangmarket.admin.entity.SiteColumn;
import com.xnx3.wangmarket.admin.util.SessionUtil;
import com.xnx3.wangmarket.plugin.base.controller.BasePluginController;

import net.sf.json.JSONObject;

/**
 * 网站-内容管理
 * @author 管雷鸣
 */
@Controller(value="AiNewsPublishPluginNewsController")
@RequestMapping("/plugin/ainewspublish/")
public class NewsController extends BasePluginController {
	@Resource
	private SqlService sqlService;
	
	/**
	 * 这个是给到 newspublish 客户端软件用的 ，用来菜单-通过url导入配置 
	 * @param password
	 * @param code 系统自动赋予的一个可以发布信息的栏目代码
	 */
	@RequestMapping(value="aiNewsPublishImport.do")
	@ResponseBody
	public String aiNewsPublishImport(HttpServletRequest request, 
			@RequestParam(required = true , defaultValue="") String password,
			@RequestParam(required = true , defaultValue="") String code){
		
		BaseVO checkVO = checkPassword(password);
		if(checkVO.getResult() - BaseVO.FAILURE == 0) {
			return checkVO.getInfo();
		}
		System.out.println(getProtocolHostAndPort(request));
		Site site = getSite();
		
		JSONObject json = new JSONObject();
		json.put("keyword", site.getName());
		json.put("key", "");
		json.put("generateNumber", "3");
		json.put("publishNewsUrl", getProtocolHostAndPort(request)+"/plugin/ainewspublish/save.json?code="+code+"&password="+password);
		
		return StringUtil.StringToUtf8(json.toString());
	}
	
	
	/**
	 * 发布 文章
	 * <p><b>注意:</b>针对大量文章情况，我们强烈建议你使用我们的 ai-seo 版本，它是专门针对亿级文章数据的场景设计的，并且拥有百度、必应、谷歌等每天自动增量推送新文章收录的能力</p>
	 * @author 管雷鸣
	 * @param password 当前操作用户的登录标识 <required>
	 * 				<p>可在网站管理后台-功能插件-AI写文章 中取得 </p>
	 * @param code 要发布的文章属于哪个栏目的代码。注意，这里是栏目的栏目代码。<br/>它跟cid你只需传入其中一个即可。<br/>如果 cid 跟 code 都有传入，则以 code 为准 <example=news>
	 * @param title 文章标题 <example=我是文章标题>
	 * @param titlepic 文章图片，传入的是图片url。可先用 <a href="plugin.adminapi.site.uploadImage.json.html">/plugin/adminapi/site/uploadImage.json</a> 将图片上传 <example=http://res.zvo.cn/default.jpg>
	 * @param intro 文章简介信息 <example=我是文章的简介>
	 * @param text 文章的正文，详细内容，也就是富文本编辑器编辑的，包含html的内容 <example=我是正文内容>
	 * @return 是否保存成功的结果
	 */
	@RequestMapping(value="save.json", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO saveNews(HttpServletRequest request, 
			@RequestParam(required = true , defaultValue="") String password,
			@RequestParam(required = true , defaultValue="") String code,
			@RequestParam(required = true , defaultValue="") String title,
			@RequestParam(required = false , defaultValue="") String titlepic,
			@RequestParam(required = false , defaultValue="") String intro,
			@RequestParam(required = false , defaultValue="") String text){
		
		BaseVO checkVO = checkPassword(password);
		if(checkVO.getResult() - BaseVO.FAILURE == 0) {
			return checkVO;
		}
		Site site = SessionUtil.getSite();
		
		//根据code_name获取栏目的cid
		int cid = 0;
		if(code != null || code.length() > 0) {
			Map<String, Object> parameterMap = new HashMap<String, Object>();
			parameterMap.put("codeName", code);
			List<SiteColumn> list = sqlService.findByHql("FROM SiteColumn sc WHERE sc.siteid = "+site.getId()+" AND code_name = :codeName", parameterMap, 1);
			if(list.size() == 0) {
				return BaseVO.failure("栏目代码 "+code+" 未发现此栏目存在");
			}
			cid = list.get(0).getId();
		}else {
			return BaseVO.failure("请传入栏目代码 code");
		}
		
		News news = new News();
		news.setCid(cid);
		news.setIntro(intro);
		news.setTitle(title);
		news.setTitlepic(titlepic);
		
		return ((com.xnx3.wangmarket.admin.controller.NewsController)SpringUtil.getBean("newsController")).saveNews(news, text, request);
	}
	
	/**
	 * 校验password的合法性
	 * @param password 传入的是 siteid_user.password ，如  219_xxxxxxxhjakshdkhasads
	 * @return
	 */
	private BaseVO checkPassword(String password) {

		//验证 password
		if(password.indexOf("_") < 0) {
			return BaseVO.failure("password 异常");
		}
		String[] ps = password.split("_");
		if(ps.length != 2) {
			return BaseVO.failure("password 校验异常");
		}
		int siteid = Lang.stringToInt(ps[0], 0);
		String userPassword = ps[1];
		
		User user = sqlService.findAloneByProperty(User.class, "password", userPassword);
		if(user == null) {
			return BaseVO.failure("password 错误");
		}
		Site site = sqlService.findById(Site.class, siteid);
		if(site == null) {
			return BaseVO.failure("password 站点错误");
		}
		if(site.getUserid() - user.getId() != 0) {
			return BaseVO.failure("越权！");
		}
		
		//设置登录状态
		SessionUtil.setUser(user);
		SessionUtil.setSite(site);
		
		return BaseVO.success();
	}
	
	
	public static String getProtocolHostAndPort(HttpServletRequest request) {
        String protocol = request.getScheme();
        String host = request.getHeader("host");
        if (host == null) {
            host = request.getServerName();
            int port = request.getServerPort();
            if (port!= 80 && port!= 443) {
                host += ":" + port;
            }
        }
        return protocol + "://" + host;
    }
}